//
//  YJGetVerificationVC.m
//  YJB
//
//  Created by YJB on 16/9/7.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "YJGetVerificationVC.h"
#import "Masonry.h"
#import "YJGCDTimer.h"
#import "YJNetworkTool.h"
#import "YJResetPWDVC.h"
#import "YJRegistVC.h"

@interface YJGetVerificationVC ()<UITextFieldDelegate>
/** 记录上一次文本框中的内容以及光标的位置 */
@property(nonatomic,strong)NSString  *previousTextFieldContent;
@property(nonatomic,strong)UITextRange  *previousSelection;

@property(strong, nonatomic)UITextField *userTel;
@property(nonatomic,strong)UIButton    *checkBtn;
@property(nonatomic,strong)UITextField *msgVertify;
@property(nonatomic,strong) UIButton   *getVertifyBtn;
@property(nonatomic,strong)UIButton    *nextBtn;
@property(nonatomic,strong)YJGCDTimer *timer;
@end

@implementation YJGetVerificationVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationItem.title = _isRegister?@"注册":@"忘记密码";
    self.view.backgroundColor = WHITECOLOR;
    [self nextBtn];
    _timer = [[YJGCDTimer alloc]init];
    [self.userTel becomeFirstResponder];
}


#pragma mark ---------------------- tel输入框
- (UITextField *)userTel
{
    if (_userTel == nil)
    {
        _userTel = [[UITextField alloc] init];
        _userTel.delegate = self;
        [_userTel addTarget:self action:@selector(reformatAsPhoneNumber:) forControlEvents:UIControlEventEditingChanged];
        _userTel.placeholder = @"请填写您的手机号";
        [_userTel setBackground:Image(@"login_inputView_bg")];
        _userTel.clearButtonMode = UITextFieldViewModeAlways;
        _userTel.keyboardType =  UIKeyboardTypeNumberPad;
        UIView *leftView = [[UIView alloc]init];
        leftView.width = 10;
        _userTel.leftView = leftView;
        _userTel.leftViewMode = UITextFieldViewModeAlways;
        [self.view addSubview:_userTel];
        [_userTel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(17.5);
            make.right.mas_equalTo(-17.5);
            make.top.mas_equalTo(100);
            make.height.mas_equalTo(40);
        }];
    }
    return _userTel;
}

- (UIButton *)getVertifyBtn
{
    if (_getVertifyBtn == nil)
    {
        _getVertifyBtn = [[UIButton alloc] init];
        [_getVertifyBtn setBackgroundImage:Image(@"button_icon") forState:UIControlStateNormal];
        [_getVertifyBtn setBackgroundImage:Image(@"button_icon_HL") forState:UIControlStateDisabled];
        [_getVertifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _getVertifyBtn.titleLabel.font = FONT(15);
        [_getVertifyBtn addTarget:self action:@selector(getVertifyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_getVertifyBtn];
        [_getVertifyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.userTel.mas_right);
            make.top.mas_equalTo(self.userTel.mas_bottom).offset(12);
            make.height.mas_equalTo(40);
            make.width.mas_equalTo(100);
        }];
    }
    return _getVertifyBtn ;
}

- (UITextField *)msgVertify
{
    if (_msgVertify == nil)
    {
        _msgVertify = [[UITextField alloc] init];
        _msgVertify.placeholder = @"填写验证码";
        [_msgVertify setBackground:Image(@"login_inputView_bg")];
        _msgVertify.clearButtonMode = UITextFieldViewModeAlways;
        UIView *leftView = [[UIView alloc]init];
        leftView.width = 10;
        _msgVertify.leftView = leftView;
        _msgVertify.leftViewMode = UITextFieldViewModeAlways;
        [self.view addSubview:_msgVertify];
        [_msgVertify mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.userTel.mas_left);
            make.right.mas_equalTo(self.getVertifyBtn.mas_left).offset(-12);
            make.top.mas_equalTo(self.userTel.mas_bottom).offset(12);
            make.height.mas_equalTo(self.getVertifyBtn.mas_height);
        }];
    }
    return _msgVertify;
}

- (UIButton *)nextBtn
{
    if (_nextBtn == nil)
    {
        _nextBtn = [[UIButton alloc]init];
        [_nextBtn setBackgroundImage:Image(@"button_icon") forState:UIControlStateNormal];
        [_nextBtn setBackgroundImage:Image(@"button_icon_HL") forState:UIControlStateHighlighted];
        [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [_nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_nextBtn];
        [_nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(17.5);
            make.right.mas_equalTo(-17.5);
            make.height.mas_equalTo(45);
            make.top.mas_equalTo(self.msgVertify.mas_bottom).offset(20);
        }];
    }
    return _nextBtn;
}

- (void)getVertifyBtnClick:(UIButton *)button
{
    NSString *number = [_userTel.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![number isMobile])
    {
        [MBProgressHUD showError:@"请输入正确的手机号"];
    }else
    {
        [self requestVerification];
    }
}

//验证验证码
- (void)checkVerification
{
    [self.view endEditing:YES];
    NSString *number = [_userTel.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"action"] = @"check_verify_code";
    params[@"makegold"] = @{@"phone":number,
                            @"verify":self.msgVertify.text,
                            @"user_info":@"admin",
                            @"phone_info":@"iOS",
                            @"md5_key":[[[@"admin"stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key] md5]};
    [MBProgressHUD showMessage:@"" toView:self.view];
    [YJNetworkTool postWithUrl:NEWURL(@"verify_code.php") parameters:params success:^(id responseObject)
     {
         [MBProgressHUD hideHUDForView:self.view];
         NSString *code = responseObject[@"return"][@"code"];
         if (code.integerValue == 200)
         {
             [_timer cancel];
             self.getVertifyBtn.enabled = YES;
             [self.getVertifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
             if (_isRegister)
             {
                 YJRegistVC *registVC = [[YJRegistVC alloc]init];
                 registVC.telStr = number;
                 [self.navigationController pushViewController:registVC animated:YES];
             }else
             {
                 YJResetPWDVC *resetVC = [[YJResetPWDVC alloc]init];
                 resetVC.telephone = number;
                 resetVC.isPushFromSetting = _isPushFromSetting;
                 [self.navigationController pushViewController:resetVC animated:YES];
             }
         }else
         {
             NSString *message = responseObject[@"return"][@"message"];
             [MBProgressHUD showError:message toView:self.view];
         }
     } failure:^(NSError *error) {
         [MBProgressHUD hideHUDForView:self.view];
         [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
     }];
}

- (void)requestVerification
{
    [self.view endEditing:YES];
    NSString *number = [_userTel.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"action"] = @"get_verify_code";
    params[@"makegold"] = @{@"phone":number,
                           @"user_info":@"admin",
                           @"phone_info":@"iOS",
                           @"md5_key":[[[@"admin" stringByAppendingString:@"iOS"]stringByAppendingString:appMd5Key]md5]};
    [MBProgressHUD showMessage:@"正在发送验证码" toView:self.view];
    [YJNetworkTool postWithUrl:NEWURL(@"verify_code.php") parameters:params success:^(id responseObject)
     {
         [MBProgressHUD hideHUDForView:self.view];
         NSString *code = responseObject[@"return"][@"code"];
         if (code.integerValue == 200)
         {
             [MBProgressHUD showSuccess:@"验证码已发送至您手机" toView:self.view];
             //开启倒计时
             [self startTimer];
         }else
         {
             NSString *message = responseObject[@"return"][@"message"];
             [MBProgressHUD showError:message toView:self.view];
         }
        
     } failure:^(NSError *error) {
         [MBProgressHUD hideHUDForView:self.view];
         [MBProgressHUD showError:@"网络不佳，稍后重试" toView:self.view];
     }];
}

- (void)startTimer
{
    self.getVertifyBtn.enabled = NO;
    YJWeakSelf
    __block int count = 60;
    [_timer startTimerWithHandlerBlock:^{
        NSString *title = [NSString stringWithFormat:@"%d秒后重发",--count];
       [weakSelf.getVertifyBtn setTitle:title forState:UIControlStateDisabled];
        if (count == -1)
        {
        [weakSelf.getVertifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        weakSelf.getVertifyBtn.enabled = YES;
        [weakSelf.timer cancel];
        }
    }];
}

- (void)nextBtnClick
{
    if (self.userTel.text.length == 0 || self.msgVertify.text.length == 0)
    {
        [MBProgressHUD showError:@"请输入完整信息" toView:self.view];
        return;
    }
    [self checkVerification];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)dealloc
{
    [self.timer cancel];
}

#pragma mark - 手机号码分隔
/**
 *  3-3-4手机号码分隔
 */
-(void)reformatAsPhoneNumber:(UITextField *)textField {
    //判断正确的光标位置
    NSUInteger targetCursorPostion = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
    NSString *phoneNumberWithoutSpaces = [self removeNonDigits:textField.text andPreserveCursorPosition:&targetCursorPostion];
    if([phoneNumberWithoutSpaces length]>11) {
        //避免超过11位的输入
        textField.text = _previousTextFieldContent;
        textField.selectedTextRange = _previousSelection;
        return;
    }
    
    NSString *phoneNumberWithSpaces = [self insertSpacesEveryFourDigitsIntoString:phoneNumberWithoutSpaces andPreserveCursorPosition:&targetCursorPostion];
    
    textField.text = phoneNumberWithSpaces;
    //设置光标位置
    UITextPosition *targetPostion = [textField positionFromPosition:textField.beginningOfDocument offset:targetCursorPostion];
    [textField setSelectedTextRange:[textField textRangeFromPosition:targetPostion toPosition:targetPostion]];
}

/**
 *  除去非数字字符，确定光标正确位置
 *
 *  @param string         当前的string
 *  @param cursorPosition 光标位置
 *
 *  @return 处理过后的string
 */
- (NSString *)removeNonDigits:(NSString *)string andPreserveCursorPosition:(NSUInteger *)cursorPosition {
    NSUInteger originalCursorPosition =*cursorPosition;
    NSMutableString *digitsOnlyString = [NSMutableString new];
    
    for (NSUInteger i=0; i<string.length; i++) {
        unichar characterToAdd = [string characterAtIndex:i];
        
        if(isdigit(characterToAdd)) {
            NSString *stringToAdd = [NSString stringWithCharacters:&characterToAdd length:1];
            [digitsOnlyString appendString:stringToAdd];
        }
        else {
            if(i<originalCursorPosition) {
                (*cursorPosition)--;
            }
        }
    }
    return digitsOnlyString;
}

/**
 *  将空格插入我们现在的string 中，并确定我们光标的正确位置，防止在空格中
 *
 *  @param string         当前的string
 *  @param cursorPosition 光标位置
 *
 *  @return 处理后有空格的string
 */
- (NSString *)insertSpacesEveryFourDigitsIntoString:(NSString *)string andPreserveCursorPosition:(NSUInteger *)cursorPosition{
    NSMutableString *stringWithAddedSpaces = [NSMutableString new];
    NSUInteger cursorPositionInSpacelessString = *cursorPosition;
    
    for (NSUInteger i=0; i<string.length; i++) {
        if(i>0){
            if(i==3 || i==7) {
                [stringWithAddedSpaces appendString:@" "];
                if(i<cursorPositionInSpacelessString) {
                    (*cursorPosition)++;
                }
            }
        }
        unichar characterToAdd = [string characterAtIndex:i];
        NSString *stringToAdd = [NSString stringWithCharacters:&characterToAdd length:1];
        [stringWithAddedSpaces appendString:stringToAdd];
    }
    return stringWithAddedSpaces;
}

#pragma mark - UITextFieldDelegate
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    _previousSelection = textField.selectedTextRange;
    _previousTextFieldContent = textField.text;
    return YES;
}

@end
